import { fetchEventSource } from '@microsoft/fetch-event-source'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useStrategyStore = defineStore('selectStore', () => {
  // 选股列表
  const selectStockList = ref<string[]>([])
  // 日内动量分析列表
  const analyzeIntradayMovementList = ref<{
    news: number
    vmap: number
    time: number
    signal: number
  }[]>([])

  let controller: AbortController = new AbortController()
  async function selectLowIntensiveChipStrategy (
    num: string,
    window: string,
    profit_rate: string,
    concentration_90: string,
    concentration_70: string) {
    if (controller) {
      controller.abort()
      selectStockList.value = []
    }
    selectStockList.value = []
    controller = new AbortController()
    await fetchEventSource(`/sse/strategy/select/LowIntensiveChipStrategy?window=${window}
    &num=${num}
    &profit_rate=${profit_rate}
    &concentration_90=${concentration_90}
    &concentration_70=${concentration_70}`, {
      signal: controller.signal,
      async onopen (response) {
        selectStockList.value = []
        console.log('onopen-select-LowIntensiveChipStrategy', response)
      },
      onmessage (msg) {
        const res = JSON.parse(msg.data)
        if (res.code === 1 && !selectStockList.value.includes(res.data)) {
          console.log('select-LowIntensiveChipStrategy', res.data)
          selectStockList.value.push(res.data)
        }
      },
      onclose () {
        console.log('onclose-select-LowIntensiveChipStrategy')
      },
      onerror (err) {
        controller.abort()
        console.log('onerror-select-LowIntensiveChipStrategy', err)
      },
    })
  }
  async function analyzeIntradayMovementStrategy (code: string, window: string, period: string) {
    if (controller) {
      controller.abort()
      analyzeIntradayMovementList.value = []
    }
    analyzeIntradayMovementList.value = []
    controller = new AbortController()
    await fetchEventSource(`/sse/strategy/analyze/IntradayMovementStrategy?code=${code}&window=${window}&period=${period}`, {
      signal: controller.signal,
      async onopen (response) {
        console.log('onopen-analyze-IntradayMovementStrategy', response)
        analyzeIntradayMovementList.value = []
      },
      onmessage (msg) {
        const res = JSON.parse(msg.data)
        if (res.code === 1 && !analyzeIntradayMovementList.value.includes(res.data)) {
          console.log(analyzeIntradayMovementList.value)
          analyzeIntradayMovementList.value.push(res.data)
        }
      },
      onclose () {
        console.log('onclose-analyze-IntradayMovementStrategy')
      },
      onerror (err) {
        controller.abort()
        console.log('onerror-select-LowIntensiveChipStrategy', err)
      },
    })
  }
  return {
    selectStockList,
    analyzeIntradayMovementList,
    selectLowIntensiveChipStrategy,
    analyzeIntradayMovementStrategy,
  }
})
